package com.tanhua.app.controllerservice;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.api.db.QuestionApi;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.FriendsApi;
import com.tanhua.api.mongo.RecommendUserApi;
import com.tanhua.api.mongo.UserLikeApi;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.vo.*;
import com.tanhua.template.HuanXinTemplate;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TanHuaService {


    @Reference
    private RecommendUserApi recommendUserApi;


    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private QuestionApi questionApi;
    @Reference
    private FriendsApi friendsApi;
    @Reference
    private UserLikeApi userLikeApi;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;


    public ResponseEntity todayBest() {

        // 1 根据当前登录用户的id查询缘分值最高的女神id （mongoDB）
        RecommendUser recommendUser =recommendUserApi.findBytodayBest(UserHolder.getUser().getId());
        //2 根据女神的id去userInfo表中查询女神的信息  (mysql)
        UserInfo userInfo = userInfoApi.findUserInfo(recommendUser.getUserId());
        //模拟数据 没有缘分人都是2号
        if(recommendUser==null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(2L); //在这里是写死的  你可以做成随机的
            recommendUser.setScore(99.0); //这里的得分也是写死的
        }

        //3 将女生信息和缘分值封装到vo中
        TodayBest todayBest = new TodayBest();
        todayBest.setFateValue(recommendUser.getScore().longValue());
        BeanUtil.copyProperties(userInfo,todayBest);
        todayBest.setTags(userInfo.getTags().split(","));
        return ResponseEntity.ok(todayBest);
    }

    public ResponseEntity recommendation(Integer page, Integer pagesize) {

        //1 分页查询女神的id和缘分值
        PageBeanVo pageBean= recommendUserApi.findRecommendation(page,pagesize,UserHolder.getUser().getId());
        List<RecommendUser> items = (List<RecommendUser>) pageBean.getItems();

        // 没有佳人（假数据）
        if(items.size()==0){
            items=fromtuijianren();
        }


        List<TodayBest> list=new ArrayList<TodayBest>();
        //有佳人
        if(CollectionUtil.isNotEmpty(items)){
            //2 根据女神id查询女神信息
            for (RecommendUser recommendUser : items) {
                UserInfo userInfo = userInfoApi.findUserInfo(recommendUser.getUserId());

                //3 将女神信息和缘分值封装给vo
                TodayBest todayBest = new TodayBest();
                BeanUtil.copyProperties(userInfo,todayBest);
                todayBest.setTags(userInfo.getTags().split(","));

                todayBest.setFateValue(recommendUser.getScore().longValue());

                list.add(todayBest);
            }
        }

        //4 将vo数据给pageBean
        pageBean.setItems(list);

        //5 返回pageBean
        return ResponseEntity.ok(pageBean);
    }


    private List<RecommendUser> fromtuijianren() {
        List<RecommendUser> list=new ArrayList<RecommendUser>();

        for(Long i=1l;i<=10;i++){
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(i);
            recommendUser.setScore(RandomUtils.nextDouble(60,99));
            list.add(recommendUser);
        }
        return list;
    }

    public ResponseEntity personalInfo(Integer jrid) {

        //根据佳人id查询佳人的信息
        UserInfo userInfo = userInfoApi.findUserInfo(jrid.longValue());
        //根据佳人id和当前登录用户查询2者之间的缘分值 recommend_user
        RecommendUser user=recommendUserApi.findScore(jrid,UserHolder.getUser().getId());
        if(user==null){
            user=new RecommendUser();
            user.setScore(99d); //假收据
        }
        // 封装佳人信息和当前登录用户之间的缘分值 给app
        TodayBest todayBest = new TodayBest();
        BeanUtil.copyProperties(userInfo,todayBest);
        todayBest.setTags(userInfo.getTags().split(","));
        todayBest.setFateValue(user.getScore().longValue());

        return ResponseEntity.ok(todayBest);
    }

    public ResponseEntity strangerQuestions(Integer userId) {

        //带着userId查询问题表
        Question question = questionApi.findQuestion(userId.longValue());

        if(question==null){
            question=new Question();
            question.setStrangerQuestion("你是GG还是MM？");
        }

        return ResponseEntity.ok(question.getStrangerQuestion());

    }

    public ResponseEntity toStrangerQuestions(Integer userId, String info) {

        //当前登录用户
        UserInfo userInfo = userInfoApi.findUserInfo(UserHolder.getUser().getId());

        //拼装环信要的数据
        Map<String,String> hxMap=new HashMap<>(); //bug: 环信要求的key value都是String
        hxMap.put("userId",userInfo.getId().toString());
        hxMap.put("nickname",userInfo.getNickname());
        //根据佳人的id获取佳人的问题
        Question question = questionApi.findQuestion(userId.longValue());
        hxMap.put("strangerQuestion",question.getStrangerQuestion());
        hxMap.put("reply",info);

        //map转换成json数据给环信
        String json = JSON.toJSONString(hxMap);
        //调用环信方法发送验证消息
        huanXinTemplate.sendMsg(userId.toString(),json);


        return ResponseEntity.ok(null);
    }

    public ResponseEntity cards() {
        Long userId = UserHolder.getUser().getId();
        List<UserInfo> userInfoList = userInfoApi.findAllUsers();
        //获取所有好友
        List<Friend> friendsList = friendsApi.findAllFriends(userId);
        List<Long> friendIdList = new ArrayList();
        for (Friend friend : friendsList) {
            Long friendId = friend.getFriendId();
            friendIdList.add(friendId);
        }

        List<TanhuaVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(userInfoList)){
            for (UserInfo userInfo : userInfoList) {
                //跳过自己
                if (userId.equals(userInfo.getId())){
                    continue;
                }
                //跳过好友
                if (friendIdList.contains(userInfo.getId())){
                    continue;
                }
                //判断是否已经喜欢
                if (userLikeApi.isLike(UserHolder.getUser().getId(),userInfo.getId())){
                    continue;
                }
                //判断是否已经不喜欢
                if (stringRedisTemplate.hasKey(StrUtil.format("tanhua_unlike_{}_{}",userId,userInfo.getId()))){
                    continue;
                }
                //加入返回的集合中
                TanhuaVo vo = new TanhuaVo();
                BeanUtils.copyProperties(userInfo,vo);
                vo.setId(userInfo.getId().intValue());
                String tags = userInfo.getTags();
                vo.setTags(tags.split(","));
                voList.add(vo);
            }
        }
        return ResponseEntity.ok(voList);
    }

    public ResponseEntity unlikeCard(Integer id) {
        stringRedisTemplate.opsForValue()
                .set(StrUtil.format("tanhua_unlike_{}_{}",UserHolder.getUser().getId(),id),"不喜欢");
        return null;
    }

    public ResponseEntity likeCard(Integer id) {
        UserLike userLike = new UserLike();
        userLike.setCreated(System.currentTimeMillis());
        userLike.setUserId(UserHolder.getUser().getId());
        userLike.setLikeUserId(id.longValue());
        userLikeApi.saveFans(userLike);
        return null;
    }
}
